import { Breadcrumb, Button, Card ,Form, Radio,  DatePicker, Table,Tag, Space, message, Modal   } from 'antd';

import React ,{useEffect, useRef, useState} from 'react';
import { Link } from 'react-router-dom';
import { getArticleLsit ,delArticleLsit } from 'api/article';
import coverSrc from 'assets/error.png'
import { EditOutlined,DeleteOutlined } from '@ant-design/icons';
import Channle from 'components/Cannle';
const { RangePicker } = DatePicker;
export default function ArticleList(props) {

  const formDateRef = useRef()
  const pageInfoRef = useRef({})

  const onFinish = (values) => {
    // console.log(18,values);
    let formDate = { ...values }
    if (formDate.status === -1) {
      delete formDate.status
      // console.log(16,formDate);
    }
    if (formDate.data) {
      const begin_pubdate = formDate.data[0].startOf('day').format('YYYY-MM-DD HH:mm:ss')
      const end_pubdate = formDate.data[1].endOf('day').format('YYYY-MM-DD HH:mm:ss')
      // console.log(21,begin_pubdate,end_pubdate);
      formDate.begin_pubdate = begin_pubdate
      formDate.end_pubdate = end_pubdate
      delete formDate.data
    }

    formDate = JSON.parse(JSON.stringify(formDate))
    // console.log(26, formDate);
    formDateRef.current = formDate
    getArticleListApi({...formDate })
  }



//   //频道列表
// const [channle ,setChannles] = useState([])
//   const loadChannles = async () => {
//     const res = await loadChannleAPI()
//     // console.log(17, res);
//     setChannles(res.data.channels)
//   }

  const [articleList ,setArticleList]  = useState([])
  const getArticleListApi = async (params) => {
    const res = await getArticleLsit(params)
    // console.log(41, res);
    setArticleList(res.data)
  }

  const handlePageChange = (page, per_page) => {
    const formDate = formDateRef.current || {}
      pageInfoRef.current = {
      page,
      per_page,
      ...formDate
     };
    getArticleListApi({page ,per_page,...formDate})
  }

  const handleArticleDel =  (id) => {
    Modal.confirm({
        title: '温馨提示',
        content: '你确定要删除文章吗',
        onOk : async() => {
          // 发送请求进行删除
          await delArticleLsit(id)
          message.success('删除成功')
          const formDate = formDateRef.current || {}
          getArticleListApi({...formDate,...pageInfoRef.current})
        },


    })

  }

  useEffect(() => {
    getArticleListApi()
  },[])

  const articleStatus = [
    { id: -1, name: '全部', color: 'magenta' },
    { id: 0, name: '草稿', color: 'orange' },
    { id: 1, name: '待审核', color: 'red' },
    { id: 2, name: '审核通过', color: 'green' },
    { id: 3, name: '审核失败', color: 'cyan' },
  ]


  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      render: (value) => {
        // console.log(47,value);
        return  value.images.length? (
         <img src={value.images[0]} alt=""  width={100} height={60}/>
        ) : (
          <img src={coverSrc} alt="" width={100} height={60}/>
        )
      }
    },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render :(value) => {

        const currentItem = articleStatus.find(item => item.id === value)

        return <Tag color={currentItem.color}>{currentItem.name}</Tag>
      }

    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      dataIndex: 'action',
      render :(value,record) => {
        return (
          <Space>
            <Button type="primary" shape="circle" icon={<EditOutlined />} onClick={()=> props.history.push(`/edit/${record.id}`)}></Button>

       <Button shape="circle" icon={<DeleteOutlined />} danger onClick={()=> handleArticleDel(record.id)} ></Button>


          </Space>
        )
      }
    },

  ]

    return <div  style={{ height: 'calc (100vh - 64px)', overflow: 'auto', padding: 24 }} >
      <Card   title ={
        <Breadcrumb>
        <Breadcrumb.Item>
          <Link to='/home'>首页</Link>
          </Breadcrumb.Item>
        <Breadcrumb.Item>
          文章列表
        </Breadcrumb.Item>
            </Breadcrumb>
        }
        bordered = {false}>
       <Form onFinish={onFinish} autoComplete='off'>
      <Form.Item
        label="状态"
        name="status"
          >
       <Radio.Group >
      <Radio value={-1}>全部</Radio>
      <Radio value={0}>草稿</Radio>
      <Radio value={1}>待审核</Radio>
      <Radio value={2}>审核通过</Radio>
      <Radio value={3}>审核失败</Radio>
      </Radio.Group>
          </Form.Item>

      <Form.Item
        label="频道"
        name="channel_id"
          >
            <Channle></Channle>
    </Form.Item>

    <Form.Item
        label="日期"
        name="data"
          >
     <RangePicker />
          </Form.Item>

          <Form.Item >
        <Button type="primary" htmlType="submit">
          筛选
        </Button>
      </Form.Item>

          <p> 共筛选到{articleList.total_count }条结果</p>
          <Table dataSource={articleList.results}
            columns={columns}
            rowKey="id"
            pagination={{
              onChange:handlePageChange,
              position: ['bottomCenter'],
              pageSize: articleList.per_page,
              total: articleList.total_count,
              current:articleList.page
            }}
          />


        </Form>



      </Card>

    </div>;
  }


